# Fig. S16: EIA Capacity by Technology Over Time
# Alex Gazmararian
# agazmararian@gmail.com
#
# Creates line plot showing planned renewable energy capacity by technology type
# with IRA passage marked.

library(tidyverse)
library(here)
library(zoo)

message("=== GENERATING FIG. S16: EIA CAPACITY BY TECHNOLOGY ===")

# Load pre-processed EIA data ----
processed_file <- here("data", "inter", "eia_processed.rds")
if (!file.exists(processed_file)) {
  stop("Processed EIA data not found. Please run process_eia.R first to generate: ", processed_file)
}

eia_processed <- readRDS(processed_file)
message("Loaded ", nrow(eia_processed), " processed EIA records")

# Prepare data ----
eia_filtered <- eia_processed %>%
  mutate(
    year_num = year(date),
    month_num = month(date)
  ) %>%
  mutate(
    technology = case_when(
      technology == "Batteries" ~ "Batteries",
      technology %in% c("Offshore Wind Turbine", "Onshore Wind Turbine") ~ "Wind",
      technology == "Solar Photovoltaic" ~ "Solar",
      TRUE ~ "Other"
    )
  )

message("Using ", nrow(eia_filtered), " projects in key technologies")

# Aggregate capacity by year-month and technology
capacity_data <- eia_filtered %>%
  group_by(year_num, month_num, technology) %>%
  summarize(
    cap_mw = sum(net_summer_capacity_mw, na.rm = TRUE),
    .groups = "drop"
  ) %>%
  mutate(date = as.yearmon(paste0(year_num, "-", sprintf("%02d", month_num)))) %>%
  mutate(technology = factor(
    technology, 
    levels = rev(c("Other", "Batteries", "Wind", "Solar")), 
    ordered = TRUE
  ))

# Create figure ----
fig_s16 <- capacity_data %>%
  ggplot(aes(x = date, y = cap_mw / 1000, color = technology, lty = technology)) +
  geom_vline(
    xintercept = as.yearmon("2022-08"), 
    lty = "dashed",
    color = "red",
    linewidth = 1
  ) +
  geom_line(linewidth = 1.25) +
  annotate(
    "text", 
    x = as.yearmon("2022-08"), y = Inf,
    label = "IRA passed\nAug. 16, 2022", 
    hjust = 1.05, vjust = 1.1,
    size = 3
  ) +
  scale_x_yearmon(
    breaks = seq(as.yearmon("2015-01"), as.yearmon("2025-01"), by = 1),
    labels = function(x) format(x, "%Y"),
    expand = c(0, 0)
  ) +
  scale_y_continuous(expand = c(0, 0)) +
  scale_color_viridis_d() +
  theme_classic(base_size = 14) +
  theme(
    panel.grid = element_blank(),
    legend.position = "inside",
    legend.position.inside = c(.1, .9),
    axis.ticks = element_blank(),
    axis.text.x = element_text(angle = 45, hjust = 1)
  ) +
  labs(
    x = "Year-Month", 
    y = "Planned capacity (GW)",
    color = NULL,
    lty = NULL
  )

# Save figure ----
output_path <- here("output", "pnas", "figures", "fig_S16_eia_capacity_by_technology.pdf")
ggsave(
  output_path,
  plot = fig_s16,
  width = 6.5, height = 6.5 / 1.618,
  scale = 1.5
)

message("[OK] Fig. S16 saved to: ", output_path)

